<template>
  <div class="search-suggestion">
    <template v-if="suggestions.length !== 0">
      <div
        class="box-text"
        v-for="(item, index) in suggestions"
        :key="index"
        @click="$emit('search', item.realName)"
      >
        <div class="box-img">{{ imgName[index] }}</div>
        <div class="box-div">
          <span class="box-title" v-html="highlight(item.realName)"></span>
          <div class="box-content">
            <span>{{ item.phone }}</span
            ><span class="box-line">|</span><span></span>{{ item.orgName }}
          </div>
        </div>
      </div>
    </template>
    <div class="cannot-find" v-else>
      找不到关于“ <span>{{ searchText }}</span> ”的联系人
    </div>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/serach'
import { debounce } from 'lodash'
export default {
  data() {
    return {
      suggestions: [], // 联想建议数据列表
      imgName: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(q) {
      const Q = {
        realName: q,
        pageNumber: 1,
        pageSize: 5
      }
      try {
        const { data: res } = await getSearchSuggestions(Q)
        this.suggestions = res.data.records
        console.log(this.suggestions)
        this.imgName = this.suggestions.map(item => item.realName.split('')[0])
      } catch (error) {
        this.$toast('获取数据失败, 请稍后重试')
      }
    },
    // 高亮
    highlight(text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  },
  watch: {
    searchText: {
      handler: debounce(function(value) {
        this.loadSearchSuggestions(value)
      }, 200),
      // 该回调将会在侦听开始以后被立即调用
      immediate: true
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  .box-text {
    height: 156px;
    margin-left: 40px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e5e5e5;
    .box-img {
      height: 64px;
      width: 64px;
      line-height: 64px;
      text-align: center;
      margin-right: 27px;
      border-radius: 50%;
      background-color: #2489f2;
      color: #fff;
      font-size: 28px;
    }
    .box-div {
      .box-title {
        font-size: 30px;
        color: #101010;
      }
      /deep/.active {
        color: #2289f2;
      }
      .box-content {
        margin-top: 13px;
        font-size: 24px;
        color: #888888;
        .box-line {
          margin: 0 20px;
        }
      }
    }
  }
  .cannot-find {
    margin-top: 70px;
    text-align: center;
    font-size: 26px;
    color: #999999;
  }
}
</style>
